import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Row, Col, Tooltip } from 'antd';
import 'moment/locale/zh-cn';
import { PrimaryGhostC, TableC, SecondHeaderC, XYAxisChartsC, PrimaryC } from '../../../../../comps';
import Style from '../../index.less';
import colors from '../../../../../css/colors';
import ChartsPie from './ChartsPie';
import { fixedNum } from '../../../../../utils/utils';
import upPng from '../../../../../assets/commom/up_arrow.png';
import downPng from '../../../../../assets/commom/down_arrow.png';
import { exportFile } from '@/src/utils/commonFunc';
import moment from 'moment';
@connect(({ portfolioOptimizationM, workStationM, loading }) => ({
  portfolioOptimizationM,
  workStationM,
  loading,
}))
export default class TotalViewC extends PureComponent {
  state = {
    id: undefined, //分析结果的唯一id
    initWeightCharts: [], //初始权重charts数据
    optimizeWeightCharts: [], //初始权重charts数据
    performCompColumns: [
      {
        title: '',
        key: 'index',
      },
      {
        title: '初始组合',
        key: 'initConfig',
      },
      {
        title: '优化后组合',
        key: 'optimizeConfig',
      },
    ],
    configColumns: [
      {
        title: '股票代码',
        key: 'code',
      },
      {
        title: '股票名称',
        key: 'name',
      },
      {
        title: this.props.fromBarra ? '优化前权重(%)' : '初始权重',
        key: 'initWeight',
      },
      {
        title: this.props.fromBarra ? '优化后权重(%)':'优化后权重',
        key: 'optimizeWeight',
      },
      {
        title: this.props.fromBarra ? '权重变化(%)':'权重变化',
        key: 'weightDifference',
      },
    ],
  };

  componentDidMount() {
    const {
      data: {
        config: { dataSource = [] },
      },
    } = this.props;
    this.setState({
      initWeightCharts: [...this.getPiesData(dataSource, 'initWeight')],
      optimizeWeightCharts: [...this.getPiesData(dataSource, 'optimizeWeight')],
    });
  }
  componentWillUnmount() {
    // 离开前清除models数据
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.data && this.state.id != nextProps.data?.id) {
      //更新值
      const {
        data: {
          config: { dataSource = [] },
        },
      } = nextProps;
      this.setState({
        id: nextProps.data.id,
        initWeightCharts: [...this.getPiesData(dataSource, 'initWeight')],
        optimizeWeightCharts: [...this.getPiesData(dataSource, 'optimizeWeight')],
      });
    }
  }
  getPiesData = (dataSource, type) => {
    let piesData = [];
    if (type == 'optimizeWeight') {
      let temp = _.cloneDeep(
        dataSource.map((item) => {
          return { name: item.name, value: item[type] };
        }),
      );
      temp.sort((x, y) => {
        if (x.value < y.value) {
          return 1;
        }
        if (x.value > y.value) {
          return -1;
        }
        return 0;
      });
      piesData = temp.splice(0, 10);
    } else {
      piesData = dataSource
        .map((item) => {
          return { name: item.name, value: item[type] };
        })
        .splice(0, 10);
      piesData.sort((x, y) => {
        if (x.value < y.value) {
          return 1;
        }
        if (x.value > y.value) {
          return -1;
        }
        return 0;
      });
    }
    let sum = 0;
    piesData.map((item) => {
      sum = sum + item.value;
    });
    if (100 - sum <= 0) return piesData || [];
    piesData.push({ name: '其他', value: 100 - sum });
    return piesData || [];
  };

  performCompTable = () => {
    //组合绩效对比对应的表格
    const {
      data: {
        performComp: { dataSource = [] },
      },
    } = this.props;
    let columns = this.state.performCompColumns;
    columns &&
      columns.map((item, index) => {
        if (item.key == 'initConfig') {
          // item.type = 'number';
          item.align="right"
        }
        item.width = '33.33%';
        if (item.key == 'index') {
          item.render = (text) => {
            if (text == '平均收益') {
              return (
                <span>
                  {text}&nbsp;
                  <Tooltip title={'分析区间内的日平均收益'}>
                    <QuestionCircleOutlined />
                  </Tooltip>
                </span>
              );
            }
            if (text == '期末资金') {
              return (
                <span>
                  {text}&nbsp;
                  <Tooltip title={'期末组合剩余虚拟资金'}>
                    <QuestionCircleOutlined />
                  </Tooltip>
                </span>
              );
            }
            if (text == '初始资金') {
              return (
                <span>
                  {text}&nbsp;
                  <Tooltip title={'期初组合虚拟资金，统一取100W'}>
                    <QuestionCircleOutlined />
                  </Tooltip>
                </span>
              );
            }
            return text;
          };
        }
      });
    return <TableC columns={columns} dataSource={dataSource} rowKey='index' hidePage={true} />;
  };
  configTable = () => {
    //组合配置对应的表格
    const {
      data: {
        config: { dataSource = [] },
      },
    } = this.props;
    let columns = this.state.configColumns;
    columns &&
      columns.map((item) => {
        if (item.key != 'code' && item.key != 'name') {
          item.type = 'number';
          item.render = (text) => {
            return fixedNum(text, 2);
          };
        }
        if (item.key != 'code') {
          item.width = parseFloat(100 / columns.length) + '%';
        }
        if (item.key == 'weightDifference') {
          item.render = (text) => {
            const styleObj = {
              verticalAlign: 'top',
              paddingTop: '4px',
            };
            const styleObj1 = {
              verticalAlign: 'top',
              paddingTop: '5px',
            };
            if (text > 0) {
              return (
                <span style={{ color: colors.debtAndProfit.text[0] }}>
                  {text} <img src={upPng} style={styleObj}></img>
                </span>
              );
            } else if (text < 0) {
              return (
                <span style={{ color: colors.debtAndProfit.text[1] }}>
                  {text} <img src={downPng} style={styleObj1}></img>
                </span>
              );
            } else {
              return <span style={{ paddingRight: '11px' }}>{text} </span>;
            }
          };
        }
      });
    return <TableC columns={columns} dataSource={dataSource} rowKey='code' hidePage={true} scroll={dataSource.length > 8 ? { y: 264 } : {}} />;
  };

  export = () => {
    //导出文件 需要先请求token
    exportFile('thfx/optimization/downloadOptimizedAllocation', { id: this.state.id });
  };
  //一键调仓 barra工作台
  adjustHold = () => {
    const {
      data: {
        config: { dataSource = [] },
      },
      row,
    } = this.props;
    this.props.dispatch({
      type: 'workStationM/setState',
      payload: {
        adjustArgs: { 
          productCode: row?.portfolio, 
          date: moment(row?.positionDate).format('YYYY-MM-DD'),
          holdingInfos: dataSource.map((item) => {
                          return {
                            tradingCode: item.code,
                            amount: parseFloat((item.optimizeWeight||0)/100), //优化后权重
                            holdingDate: moment(row?.positionDate).format('YYYY-MM-DD'), //持仓日期yyyy-MM-dd   是取得当时的持仓日期
                            type: '1', //固定格式
                          };}),
            },
       },
    });
    // this.props.dispatch({
    //   type: 'optimizationM/changeMyPosition',
    //   payload: {
    //     portfolioId: row?.portfolio,
    //     holdingInfos: dataSource.map((item) => {
    //       return {
    //         tradingCode: item.code,
    //         amount: parseFloat((item.optimizeWeight||0)/100), //优化后权重
    //         holdingDate: moment(row?.positionDate).format('YYYY-MM-DD'), //持仓日期yyyy-MM-dd   是取得当时的持仓日期
    //         type: '1', //固定格式
    //       };
    //     }),
    //   },
    //   callback: () => {
    //     //如果一键调仓成功时  更新数据,持仓设置组件捕捉变化
    //     console.log(moment(row?.positionDate).format('YYYY-MM-DD'));
    //     
    //   },
    // });
  };
  //判断组合是虚拟还是模拟 真实无一键调仓按钮
  getType = () => {
    const {
      workStationM: { productTableList = [] },
    } = this.props;
    let productObj = productTableList.filter((item) => item.portfolioId == this.props.row?.portfolio);
    return productObj[0]?.portfolioType == 2;
  };
  render() {
    const { initWeightCharts, optimizeWeightCharts } = this.state;
    const {
      data: { exposureComp = {} },
      fromBarra,
    } = this.props;
    const {
      data: {
        config: { dataSource = [] },
      },
      loading,
    } = this.props;
    var clientWidth = document.body.clientWidth;
    var minWidth = clientWidth - 220 - 100; //因柱状图开始很小 所以给个最小宽度
    //barra工作台过来的不需要饼图
    if(fromBarra&&exposureComp.series&&exposureComp.series.length){
      let series=exposureComp.series;
      series&&series.map(item=>{
        if(item.data){
          let data=[]
          item.data?.map(x=>{
            data.push((x*100).toFixed(2))
          })
          item.data=[...data]
        }
      })
      exposureComp.series=series
    }
    return (
      <div style={{ paddingTop: '10px' }}>
        <div className='exportBtn'>
          <SecondHeaderC
            title={'组合配置'}
            Right={
              fromBarra ? (
                this.getType() ? (
                  <PrimaryC loading={loading.effects['optimizationM/changeMyPosition'] == true} title={'一键调仓'} disabled={!dataSource?.length} onClick={this.adjustHold} />
                ) : null
              ) : (
                <PrimaryGhostC title={'导出'} onClick={this.export} />
              )
            }
          />
          <div style={{ float: 'right' }}></div>
        </div>
        {this.configTable()}
        {fromBarra ? null : (
          <Row gutter={20} style={{ margin: 0 }}>
            <Col span={12} style={{ paddingTop: '20px' }}>
              <SecondHeaderC title={'初始权重'} />
              <div className='chartsClass'>
                <ChartsPie data={initWeightCharts} />
              </div>
            </Col>
            <Col span={12} style={{ paddingTop: '20px' }}>
              <SecondHeaderC title={'优化后权重'} />
              <div className='chartsClass'>
                <ChartsPie data={optimizeWeightCharts} />
              </div>
            </Col>
          </Row>
        )}
        <div >
            <div style={{ marginTop: '20px' }}>
              <SecondHeaderC title={'风险因子超额暴露度'} />
              <div style={{ minWidth: fromBarra ? minWidth / 2 : minWidth }}>
                <XYAxisChartsC
                  series={exposureComp?.series}
                  xAxis={exposureComp?.xAxis}
                  height={fromBarra ? 410 : 455}
                  yAxisUnit={['单位（%）', '']}
                  type='bar'
                  toolTipDataFormat={[(value) => value + '%']}
                />
              </div>
            </div>
          <div style={{ marginTop: '20px' }}>
            <SecondHeaderC title={'组合绩效对比'} />
            {this.performCompTable()}
          </div>
        </div>
      </div>
    );
  }
}
